--[[ Copyright 2012, Chris Ho                               ]]--
--[[ MIT License (Please read the LICENSE file for details) ]]--

Use("common/Const");
Use("common/Log");
Use("common/Position");
Use("common/Creature");
Use("common/Skill");
Use("common/Task");

-- Kill task (attack normally until dead) (not interruptible)
-- progress: progress state
-- id: who is responsible for the task
-- origin: where the task started
-- time: when the task started
-- hp: hit points at task creation
-- sp: skill points at task creation
-- target: desired attack target
Kill = {};

function Kill.Create(_pet, _target)
  local instance = Task.Create(_pet);

  instance.target = _target;

  --[[ Attack until dead ]]--
  function instance:Execute()
    Debug("Kill.Execute()");

    local motion = GetV(V_MOTION, self.target);

    -- Don't target dead things.
    if ((motion == MOTION_DEAD) or (motion < 0)) then
      Info("Kill: Target " .. self.target .. " is unavailable.");
      return self:Progress(PROGRESS_SUCCESS);
    end

    local from = Position.Find(self.id);
    local to = Position.Find(self.target);

    -- If it's too far away, just sit there.
    if (Position.Measure(from, to) >= VISIBILITY) then
      Alert("Can't reach target. (" .. motion .. ")");
      return self:Progress(PROGRESS_FAILURE);
    end

    -- Try to move in range.
    local skill = Skill.None(_pet.id);
    local range = skill:Estimate();
    local result = self:Approach(Position.Find(self.target), range);
    if (result == PROGRESS_SUCCESS) then
      -- We should be in range by now. Attack if we're in range.
      if (self:Target(skill, self.target) == PROGRESS_SUCCESS) then
        -- Keep attacking.
        return self:Progress(PROGRESS_ACTIVE);
      end
    end

    -- Keep tring to move into range.
    return self:Progress(result);
  end

  return instance;
end
